<template>
  <Dialog title="添加角色" :has-footer="false" @open="handleDialogOpen">
    <RoleTable ref="tableEl" :data="roles" max-height="500px">
      <template #end>
        <el-table-column align="center" label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button type="text" @click="handleConfirm(scope.row)">
              选择
            </el-button>
          </template>
        </el-table-column>
      </template>
    </RoleTable>
    <Pagination
      v-model:current-page="paginationData.currentPage"
      v-model:page-size="paginationData.pageSize"
      :total="paginationData.total"
      :load-list="getUnAddUsers"
    />
  </Dialog>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'

import Dialog from '@/components/Dialog/index.vue'
import Pagination from '@/components/Pagination/index.vue'
import { addRoleToDepartment, getUnAddedRoles } from '@/http/department'
import type { IRole } from '@/http/types/role'
import { IElTable } from '@/types/element-plus'

import RoleTable from '../role/RoleTable.vue'

const props = defineProps({
  ouId: {
    type: String,
    default: '',
  },
})
interface EmitsType {
  (e: 'success'): void
}
const emit = defineEmits<EmitsType>()

const paginationData = reactive({
  pageSize: 10,
  currentPage: 1,
  total: 0,
})
const roles = ref<IRole[]>([])
const tableEl = ref<IElTable>()

const handleConfirm = async (row: IRole) => {
  selected.value = [row]
  for (const i of selected.value) {
    if (!i.id) return
    await addUser(i.id, props.ouId)
  }
  emit('success')
}
const handleDialogOpen = async () => {
  await getUnAddUsers()
}

const selected = ref<IRole[]>([])

const getUnAddUsers = async () => {
  const res = await getUnAddedRoles(
    paginationData.currentPage,
    paginationData.pageSize,
    props.ouId,
  )
  roles.value = res.items
  paginationData.total = res.totalCount
}

const addUser = async (userId: string, ouId: string) => {
  await addRoleToDepartment(userId, ouId)
}
</script>

<style scoped lang="scss"></style>
